import store from '@/store'
import { Message, Notification } from 'element-ui'
import { parseMessage, parseTime } from '@/utils/sg'
const audio = new Audio('../../static/audio/notification1.mp3')
const mailAudio = new Audio('../../static/audio/mail.mp3')
const WS = {
  $ws: null, // webscoket实例
  id: undefined,
  wsURl: 'ws://localhost:8081/websocket/',
  timer: undefined,
  createWS: function(id) {
    if ('WebSocket' in window) {
      this.id = id
      try {
        if ((this.$ws === null || this.$ws.readyState !== 1)&& id ) {
          this.$ws = new WebSocket(this.wsURl + id)
          this.$ws.onopen = this.wsOpen
          this.$ws.onmessage = this.wsMessage
          this.$ws.onerror = this.wsError
          this.$ws.onclose = this.wsClose
        }
      } catch (e) {
        reconnect()
      }
    } else {
      Message.info('当前浏览器不支持webSocket，请更新浏览器或者替换以享受完整服务')
    }
  },
  wsOpen: function() {
    // this.$ws.send('连接成功')
    console.log('== websocket open ==')
    heartBeat.start()
  },
  wsMessage: function(msg) {
    heartBeat.reset()
    const data = JSON.parse(msg.data)
    if (data.type === 'mail') {
      mailAudio.play().then(r => {})
      Notification({
        iconClass: 'el-icon-s-promotion',
        title: '代办',
        message: '收到一条站内邮件',
        duration: 2000
      })
      store.dispatch('setMailContent', data).then()
    } else {
      const currentContractID = store.getters.currentContractId
      if (currentContractID !== data.fromUser.id) {
        Notification({
          iconClass: 'el-icon-chat-dot-round',
          title: '收到来自：' + data.fromUser.displayName + '的消息',
          message: parseMessage(data.content, data.type),
          duration: 2000
        })
        audio.play().then(r => {})
        store.dispatch('addUnread').then()
        const contract = {
          id: data.fromUser.id,
          displayName: data.fromUser.displayName,
          avatar: data.fromUser.avatar,
          unread: 1,
          lastContent: data.content,
          lastSendTime: parseTime(data.sendTime),
          type: data.type
        }
        store.dispatch('addUnreadContract', contract).then()
      }
      store.dispatch('setWebsocketMsg', msg.data).then()
    }
  },
  wsError: function(err) {
    Message.error('webSocket异常关闭')
    reconnect()
    console.log('== websocket error ==', err)
  },
  wsClose: function(event) {
    reconnect()
    console.log('== websocket close ==', event)
  }
}
function reconnect() {
  heartBeat.reset()
  const userInfo = localStorage.getItem("userInfo")
  if(userInfo !== null ) {
    clearTimeout(WS.timer)
    WS.timer = setTimeout(() => {
      WS.createWS(WS.id)
    }, 5000)
  }
}
const heartBeat = {
  timeout: 30000, // 心跳重连时间
  timeoutObj: null, // 定时器
  reset: function() {
    clearInterval(this.timeoutObj)
    this.start()
  },
  start: function() {
    this.timeoutObj = setInterval(function() {
      if (WS.$ws.readyState === 1) {
        const data = {
          type: 'heartbeat'
        }
        WS.$ws.send(JSON.stringify(data))
      }
    }, this.timeout)
  }
}
export default WS
